package com.dodock.android.banglapapers.ui;

import java.util.Vector;

import org.json.JSONArray;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dodock.android.banglapapers.BanglaNews;
import com.dodock.android.banglapapers.ComplexScriptHelper;
import com.dodock.android.banglapapers.InternetConnectivity;
import com.dodock.android.banglapapers.MyApplication;
import com.dodock.android.banglapapers.NewsDetails;
import com.dodock.android.banglapapers.NewsList;
import com.dodock.android.banglapapers.R;
import com.dodock.android.banglapapers.Utility;
import com.dodock.android.banglapapers.WebServerOperation;
import com.dodock.android.banglapapers.imageLoader.ImageLoader;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;

public class NewsListActivity extends BaseActivity{
	
	private ProgressDialog progressDialog;
	private boolean bError = false;
	private String categoryId = "";
	private String id = "";
	private String language = "";
	private String paperName;
	private Typeface fontBN;
	private Typeface fontEN;
	public static Vector<NewsList> newsList;
	
	private Tracker mGaTracker;
	private GoogleAnalytics mGaInstance;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
				
		//Google Analytics
		try{
		    mGaInstance = GoogleAnalytics.getInstance(this);
		    mGaTracker = mGaInstance.getTracker(getResources().getString(R.string.ga_trackingId));
		}
		catch (Exception e) {
		}
		//--Google Analytics
		
		
		id = getIntent().getExtras().getString("id");
		categoryId = getIntent().getExtras().getString("key");
		language = getIntent().getExtras().getString("language");
		paperName = getIntent().getExtras().getString("paperName");
		setContentView(R.layout.news_category);
		
		fontBN = Typeface.createFromAsset(this.getAssets(), "font/SutonnyMJ.ttf");
		fontEN = Typeface.DEFAULT;

		TextView titleView = (TextView) findViewById(R.id.title);
		if(language.equals("bn")){					
			if(Utility.isOnlyEngCharacters(paperName)){
				titleView.setTypeface(fontEN);
				titleView.setText(paperName);
			}else{
				titleView.setTypeface(fontBN);					
				titleView.setText(ComplexScriptHelper.UnicodeToAnsi(paperName));
			}
		}else{
			titleView.setTypeface(fontEN);
			titleView.setText(paperName);
		}
		
		ImageButton settingsButton = (ImageButton) findViewById(R.id.settingsBtn);
		settingsButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				settingsActivity();
			}
		});

		Button topNewsButton = (Button) findViewById(R.id.topNews);
		topNewsButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(NewsListActivity.this, TopNewsActivity.class);
				startActivity(intent);
			}
		});

		Button favouritButton = (Button) findViewById(R.id.favorite);
		favouritButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(NewsListActivity.this, FavouritNewsActivity.class);
				startActivity(intent);
			}
		});

		Button savedNewsButton = (Button) findViewById(R.id.savedNews);
		savedNewsButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(NewsListActivity.this, SavedNewsActivity.class);
				startActivity(intent);
			}
		});
		
		ImageView refreshButton = (ImageView) findViewById(R.id.refresh);
		refreshButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				loadNewsList();
			}
		});
		loadNewsList();
	}
	
	
	@Override
	protected void onResume() {
		super.onResume();
		com.facebook.Settings.publishInstallAsync(this, MyApplication.fb_app_id);
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		try {
			mGaTracker.sendView(String.format("/%s/%s", id, categoryId));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
	}
	
	private class GetNewsList extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... params) {
			getNewsListJson();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			try{
				progressDialog.dismiss();
				progressDialog = null;
				if (!bError){
					showContentView();
				}
			}
			catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
	
	private void showContentView() {
		// TODO Auto-generated method stub
		LinearLayout mainContainer = (LinearLayout) findViewById(R.id.newsCategoryMainContainer);

		for (int newsNo = 0; newsNo < newsList.size(); newsNo++) {
			LinearLayout newsCategoryLayout = (LinearLayout) LayoutInflater.from(
					getBaseContext()).inflate(R.layout.news_list_single_item, null);
			TextView titleTextview = (TextView) newsCategoryLayout.findViewById(R.id.newsListTitle);
			if(language.equals("bn")){
				titleTextview.setTypeface(fontBN);
				titleTextview.setText(ComplexScriptHelper.UnicodeToAnsi(newsList.elementAt(newsNo).getTitle()));
			}else{
				titleTextview.setTypeface(fontEN);
				titleTextview.setText(newsList.elementAt(newsNo).getTitle());
			}
			LinearLayout container = (LinearLayout) newsCategoryLayout.findViewById(R.id.newsListImageContainer);
			ImageView image = (ImageView) newsCategoryLayout.findViewById(R.id.newsListImage);
			if(!newsList.get(newsNo).getImage().equals("noimage")){
				ImageLoader imageLoader = new ImageLoader(this);
				imageLoader.DisplayImage(newsList.get(newsNo).getImage(),R.drawable.logo, image, true, container);
			}else
				image.setImageResource(R.drawable.logo);
			
			final int position = newsNo;
			newsCategoryLayout.setOnClickListener(new OnClickListener() {
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(NewsListActivity.this, NewsDetailsActivity.class);
					intent.putExtra("newsPaperId", id);
					intent.putExtra("newsId", newsList.elementAt(position).getId());
					intent.putExtra("newsNo", position);
					intent.putExtra("language", language);
					intent.putExtra("parent", "NewsList");
					startActivity(intent);
				}
			});
			mainContainer.addView(newsCategoryLayout);
		}
	}
	
	private void parseNewsListJSON(String serverResonse) throws Exception{
		// TODO Auto-generated method stub
		JSONArray jsonArray = new JSONArray(serverResonse);
		newsList = new Vector<NewsList>();
		for (int j = 0; j < jsonArray.length(); j++) {
			NewsList category = new NewsList();
			category.setId(jsonArray.getJSONObject(j).getString("id"));
			category.setTitle(jsonArray.getJSONObject(j).getString("title"));
			if(jsonArray.getJSONObject(j).has("image"))
				category.setImage(jsonArray.getJSONObject(j).getString("image"));
			else
				category.setImage("noimage");
			if(jsonArray.getJSONObject(j).has("details")){
				NewsDetails newsDetails = new NewsDetails();
				newsDetails.setId(jsonArray.getJSONObject(j).getString("id"));
				newsDetails.setSharelink(jsonArray.getJSONObject(j).getString("sharelink"));
				newsDetails.setDetailsNews(jsonArray.getJSONObject(j).getString("details"));
				newsDetails.setTitle(jsonArray.getJSONObject(j).getString("title"));
				if(jsonArray.getJSONObject(j).has("gallery")){
					Vector<String> galleryUrlList = new Vector<String>();
					JSONArray galleryArray = jsonArray.getJSONObject(j).getJSONArray("gallery");
					for(int i = 0; i < galleryArray.length(); i++){
						galleryUrlList.add(galleryArray.getJSONObject(i).getString("url"));
					}
					newsDetails.setGalleryUrlList(galleryUrlList);
					newsDetails.setGalleryFlag(true);
				}else{
					newsDetails.setGalleryUrlList(null);
				}
				category.setNewsDetailsFlag(true);	
				category.setNewsDetails(newsDetails);
			}				
			else{
				category.setNewsDetailsFlag(false);
			}
			newsList.add(category);
		}
	}
	
	private void getNewsListJson() {
		// TODO Auto-generated method stub
		String urlPath = BanglaNews.BASE_URL + "DDNGetNewsList"+"?id="+id+"&catid="+categoryId + "&appVersion="+MyApplication.app_version;
		try {
			String serverResonse = WebServerOperation.HTTPrequest(urlPath);
			parseNewsListJSON(serverResonse);
		} catch (Exception e) {
			Log.e("NewsListActivity", "getNewsListJson() : "+e.toString());
			bError = true;
		}
	}
	
	private void loadNewsList() {
		// TODO Auto-generated method stub
		if (InternetConnectivity.isConnectedToInternet(this)) {
			progressDialog = ProgressDialog.show(this, null, "Loading. Please wait...", true, false);
			GetNewsList getNewsList = new GetNewsList();
			getNewsList.execute();
		} else {
			Toast toast = Toast.makeText(this,"Enable mobile network or Wi-Fi to download data",Toast.LENGTH_LONG);
			toast.show();
		}
	}

}
